﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using sWarranty;

namespace LCUV.WEB
{
    public partial class Login : System.Web.UI.Page
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            txtUserName.Focus();

            //if (Request.Browser.Browser.ToString() == "IE")
            //    selectBrowser.Visible = true;
            string logOut = "";
            logOut = Request.QueryString["o"];
            if (logOut == "1")
            {
                Response.Cookies["LCUV_UName"].Value = null;
                Response.Cookies["LCUV_PWD"].Value = null;
                Session["UserLoginInfo"] = "";
                Session["UrltoFw"] = "Home.aspx";
                Response.Redirect("login.aspx");
            }
            else
                if (!IsPostBack)
                {
                    //auto login by cookies
                    if (Request.Cookies["LCUV_UName"] != null)
                        txtUserName.Text = Request.Cookies["LCUV_UName"].Value;
                    if (Request.Cookies["LCUV_PWD"] != null)
                        txtPass.Text = Request.Cookies["LCUV_PWD"].Value;
                    if (Request.Cookies["LCUV_UName"] != null && Request.Cookies["LCUV_PWD"] != null)
                    {
                        Entities db = new Entities();
                        var user = from t in db.TB_USER
                                   where t.ACCOUNT == txtUserName.Text
                                   select t;
                        if (user.Count() > 0)
                        {
                            user.Select(t => t.PASS == EncDec.Encrypt(txtPass.Text, ""));
                            if (user.Count() > 0)
                            {
                                Session["UserLoginInfo"] = user.ToArray();
                            }
                        }
                        Dologin();
                    }

                    Session["UserLoginInfo"] = "";

                }
        }
        public void DoLogin(object sender, EventArgs e)
        {
            Dologin();

        }
        public void Dologin()
        {
            try
            {
                if (!string.IsNullOrEmpty(txtPass.Text) && !string.IsNullOrEmpty(txtPass.Text))
                {
                    Entities db = new Entities();
                    var _user = from t in db.TB_USER
                                where t.ACCOUNT == txtUserName.Text && t.ACTIVE == 1
                                select t;
                    if (_user.Count() > 0)
                    {
                        if (_user.Single().PASS == EncDec.Encrypt(txtPass.Text, ""))
                        {
                            //Remember me
                            if (chkRememberPassword.Checked == true)
                            {
                                Response.Cookies["LCUV_UName"].Value = txtUserName.Text;
                                Response.Cookies["LCUV_PWD"].Value = txtPass.Text;
                                Response.Cookies["LCUV_UName"].Expires = DateTime.Now.AddMonths(2);
                                Response.Cookies["LCUV_PWD"].Expires = DateTime.Now.AddMonths(2);
                            }
                            else
                            {
                                Response.Cookies["LCUV_UName"].Expires = DateTime.Now.AddMonths(-1);
                                Response.Cookies["LCUV_PWD"].Expires = DateTime.Now.AddMonths(-1);
                            }
                            //set BU to View
                            if (Request.Cookies["BU"] != null)//neu co', set no' bang ja tri hien tai(ko doi)
                                Response.Cookies["BU"].Value = Request.Cookies["BU"].Value;
                            else
                                Response.Cookies["BU"].Value = DBAction.BU.ToString();
                            Response.Cookies["BU"].Expires = DateTime.Now.AddMonths(12);

                            Session["UserLoginInfo"] = _user.ToArray();

                            //log user
                            if (DBAction.LogUser == true)
                            {
                                TB_CM_SYS_LOG lg = new TB_CM_SYS_LOG();
                                lg.ID = String.Format("{0:u}", DateTime.Now);
                                lg.ACTION1 = _user.Single().ACCOUNT +  " Login";
                                lg.ENTRY_USER_ID = _user.Single().EMPNO;
                                lg.ENTRY_DATE_TIME = DateTime.Now;
                                lg.TITLE = _user.Single().ACCOUNT + " Login";
                                db.TB_CM_SYS_LOG.AddObject(lg);

                                //create log cookie
                                Response.Cookies["LastLogTime"].Value = lg.ENTRY_DATE_TIME.ToString();
                                
                                db.SaveChanges();

                            }
                            if (Session["UrltoFw"] != null)
                                if (!string.IsNullOrEmpty(Session["UrltoFw"].ToString()))
                                    Response.Redirect(Session["UrltoFw"].ToString());
                            Response.Redirect("Home.aspx");
                        }
                        else //wrong pass
                            ShowError("Wrong user information.");
                    }
                    else //login failse
                        ShowError("Wrong user information");

                    db.Dispose();
                    //error by devart , only debug to view error
                }
                else
                {
                    txtUserName.Focus();
                    ShowError("Please input information");
                }
            }
            catch (Exception ee)
            {
                ShowError(ee);
            }
        }

        public string CheckAccount()
        {
            try
            {
                Session["UserLoginInfo"] = "";
                Entities db = new Entities();
                var user = from t in db.TB_USER
                           where t.ACCOUNT == txtUserName.Text
                           select t;
                if (user.Count() > 0)
                {
                    user.Select(t => t.PASS == EncDec.Encrypt(txtPass.Text, ""));
                    if (user.Count() > 0)
                    {
                        Session["UserLoginInfo"] = user.ToArray();
                        return "1";
                    }
                    db.Dispose();
                    return "0";

                }
                else //login failse
                {
                    db.Dispose();
                    return "0";
                }
            }
            catch (Exception ee)
            {
                ShowError(ee);
                return ee.Message;
            }
        }
        //public string LogUser(IQueryable<TB_USER> u)
        //{
        //    try
        //    {
        //        Entities db = new Entities();
        //        DMS_ACCESS_HISTORY_V2 ah = new DMS_ACCESS_HISTORY_V2();
        //        var _max = (from t in db.DMS_ACCESS_HISTORY_V2 select t.ID).Max();
        //        ah.ID = Convert.ToInt32(_max) + 1;
        //        ah.USER_ID = u.Single().ID;
        //        ah.USER_ACCOUNT = u.Single().ACCOUNT;
        //        ah.EXECUTE_DATE_TIME = DateTime.Now;
        //        ah.ACCESS_QUERRY = "SELECT * FROM DMS_USER_V2 WHERE ID = '" + txtUserName.Text.ToLower() + "' && PASS = '" + txtPass.Text + "'";
        //        ah.ACCESS_COMMENT = "User login";
        //        ah.CLIENT_INFO = Context.Request.ServerVariables["REMOTE_ADDR"].ToString();


        //        db.DMS_ACCESS_HISTORY_V2.AddObject(ah);
        //        db.SaveChanges();

        //        return "1";
        //    }
        //    catch (Exception ee)
        //    {
        //        ShowError(ee);
        //        return ee.Message;

        //    }
        //}

        protected void btnLogin_Click(object sender, EventArgs e)
        {
            Dologin();
        }

        public void ShowError(string er)
        {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "abcdefgh", "<div class=\"notification error\"><div class=\"text\"><p><strong>" + er + " </strong> </p></div></div>", false);
        }
        public void ShowError(Exception ex)
        {
            if (ex.InnerException != null)
            {
                string er = ex.InnerException.Message + " at " + ex.TargetSite.Name + "()";
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "abcdefgh", "<div class=\"notification error\"><div class=\"text\"><p><strong> " + er + " </strong></p></div></div>", false);
            }
        }
        public void ShowInfo(string er)
        {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "abcdefgh", "<div class=\"notification info\"><div class=\"text\"><p><strong> " + er + " </strong></p></div></div>", false);
        }
        public void ShowInfo(Exception ex)
        {
            if (ex.InnerException != null)
            {
                string er = ex.InnerException.Message + " at " + ex.TargetSite.Name + "()";
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "abcdefgh", "<div class=\"notification info\"><div class=\"text\"><p><strong> " + er + " </strong></p></div></div>", false);
            }
        }
        public void ShowWarning(string er)
        {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "abcdefgh", "<div class=\"notification warning\"><div class=\"text\"><p><strong> " + er + " </strong></p></div></div>", false);
        }
        public void ShowWarning(Exception ex)
        {
            if (ex.InnerException != null)
            {
                string er = ex.InnerException.Message + " at " + ex.TargetSite.Name + "()";
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "abcdefgh", "<div class=\"notification warning\"><div class=\"text\"><p><strong> " + er + " </strong></p></div></div>", false);
            }
        }
        public void ShowSuccess(string er)
        {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "abcdefgh", "<div class=\"notification success\"><div class=\"text\"><p><strong> " + er + " </strong></p></div></div>", false);
        }
        public void ShowSuccess(Exception ex)
        {
            if (ex.InnerException != null)
            {
                string er = ex.InnerException.Message + " at " + ex.TargetSite.Name + "()";
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "abcdefgh", "<div class=\"notification success\"><div class=\"text\"><p><strong> " + er + " </strong></p></div></div>", false);
            }
        }
        public void ShowTip(string er)
        {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "abcdefgh", "<div class=\"notification tip\"><div class=\"text\"><p><strong> " + er + "</strong> </p></div></div>", false);
        }
        public void ShowTip(Exception ex)
        {
            if (ex.InnerException != null)
            {
                string er = ex.InnerException.Message + " at " + ex.TargetSite.Name + "()";
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "abcdefgh", "<div class=\"notification tip\"><div class=\"text\"><p><strong> " + er + " </strong></p></div></div>", false);
            }
        }

    }
}